package com.test.base.nio1.writetest;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

@Slf4j
public class WriteServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        // 注册serverChannel到selector中
        // 实际上sscKey不需要被接受，因为register的时候已经加入到selector当中去了
        SelectionKey sscKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.socket().bind(new InetSocketAddress(8080));

        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    // 设置为关注写事件
                    scKey.interestOps(SelectionKey.OP_READ);

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
                    // 将此处的while循环修改为支持异步传输的形式
                    /* version-1不支持异步，直接阻塞写入
                    while (buffer.hasRemaining()) {
                        int write = sc.write(buffer);
                        System.out.println("write" + write);
                    }*/
                    //  进行一次写入
                    int write = sc.write(buffer);
                    System.out.println(write);
                    if (buffer.hasRemaining()) {
                        // 设置为关注读也关注写
                        // 如果设置为了既是关注读也是关注写形式，那么client的read事件就会触发这个key，导致selecto的select调用成功，然后，进入写的if调用中
                        scKey.interestOps(scKey.interestOps() + SelectionKey.OP_WRITE);
                        // 将buffer作为附件
                        scKey.attach(buffer);
                    }
                }
                // 关注写事件
                else if (key.isWritable()) {
                    // 进行一次写入操作
                    //获取 socket的channel
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    int write = sc.write(buffer);
                    System.out.println(write);

                    if (!buffer.hasRemaining()) {
                        key.attach(null);
                        // 写入完成-移除对写入事件的关注
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }
}
